<template>
  <el-form
    ref="formRef"
    style="max-width: 600px"
    :model="materialInfo"
    label-width="auto"
    class="demo-ruleForm"
  >
  <el-form-item
      label="工序名"
      prop="name"
      :rules="[
        { required: true, message: 'name is required' },
      ]"
    >
      <el-input
        v-model="materialInfo.name"
        type="text"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item
      label="设备名称/型号/工艺"
      prop="equipment"
      :rules="[
        { required: true, message: 'equipment is required' },
      ]"
    >
      <el-input
        v-model="materialInfo.equipment"
        type="text"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item
      label="工序单价"
      prop="price"
      :rules="[
        { required: true, message: 'price is required' },
        // { type: 'number', message: 'price must be a number' },
      ]"
    >
      <el-input
        v-model="materialInfo.price"
        type="text"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)">Submit</el-button>
      <el-button @click="resetForm(formRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'

import type { FormInstance } from 'element-plus'

const formRef = ref<FormInstance>()

const emit = defineEmits(['submit'])

const materialInfo = reactive({
  name: '',
  price: '',
  equipment : '',
})

const checkPrice = (price:any)=>{
    
    if(!price){
      
      return false
    }
    const price1 = Number(price)
    if(price1!=price){
      return false
    }else{
      return true
    }
  }

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate( async(valid) => {
    if (valid) {
      if(checkPrice(materialInfo.price)){
        console.log('submit!')
        
        await $fetch("/api/step",{method:"POST"
          ,body:{
            name:materialInfo.name,
            price : materialInfo.price,
            equipment: materialInfo.equipment
          }
        }).then(()=>{
          emit('submit')}
        ).catch(()=>{
        console.log('error submit!')
        })
      }
      
    } else {
      console.log('error submit!')
    }
  })

}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
